# -*- coding=utf-8 -*-
from flask import current_app
from flask import g
from flask import request
from flask import session, jsonify

from iHome import constants
from iHome import db
from iHome.models import User
from iHome.utils.common import login_required
from iHome.utils.response_code import RET
from . import api
from iHome.utils.image_storage import upload_image


@api.route("/user/auth", methods=["POST"])
@login_required
def set_user_auth():
    """设置用户实名信息"""
    # 获取参数，判断参数是否有值
    data_dict = request.json
    real_name = data_dict.get("real_name")
    id_card = data_dict.get("id_card")

    if not all([real_name, id_card]):
        return jsonify(errno=RET.PARAMERR, errmsg="信息错误")

    # 查询当前用户的模型
    user_id = g.user_id
    try:
       user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    # 更新模型
    user.real_name = real_name
    user.id_card = id_card

    # 保存到数据库
    try:
       db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    # 响应结果
    return jsonify(errno=RET.OK, errmsg="保存成功")





@api.route("/user/name", methods=['POST'])
@login_required
def set_user_name():
    """修改用户名"""
    # 获取传过来的用户名，并判断是否有值
    user_name = request.json.get("name")
    if not user_name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询到当前登陆用户
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据出错")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")

    # 更新当前登陆用户的模型
    user.name = user_name

    # 保存到数据库
    try:
       db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 反应响应
    return jsonify(errno=RET.OK, errmsg="保存成功")


@api.route("/user/avatar", methods=["POST"])
@login_required
def upload_avatar():
    """上传用户头像"""

    # 获取到上传的图片文件/判断图片文件是否存在
    try:
        avatar_data = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="请求文件失败")
    # 上传文件到七牛云
    try:
       key = upload_image(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    # 上传成功之后，保存到用户标的头像字段中
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    # 设置值到用户模型圣上数据
    user.avatar_url = key

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    avatar_url = constants.QINIU_DOMIN_PREFIX +key
    return jsonify(errno=RET.OK, errmsg="上传成功", data={"avatar_url":avatar_url})


@api.route('/user')
@login_required
def get_user_info():
    """显示用户信息"""

    # 取到当前登陆用户的id
    user_id = g.user_id
    # 查询出指定的用户信息
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")
    # 组织数据进行返回
    # resp ={
    #     "name":user.name,
    #     "avartar":user.avatar_url,
    #     "user_id":user.id
    # }

    # 进行响应
    return jsonify(errno=RET.OK, errmsg = "OK", data=user.to_dict())




